package com.xnyzc.lhy.common.util;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;

@Slf4j
public class HttpUtil {

    /**
     * 获取IP
     *
     * @param request
     * @return
     * @throws Exception
     */
    public static String getIpAddr(HttpServletRequest request) throws Exception {
        String ip = request.getHeader("X-Real-IP");
        if (!Strings.isNullOrEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = request.getHeader("X-Forwarded-For");
        if (!Strings.isNullOrEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个为真实IP。
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        } else {
            return request.getRemoteAddr();
        }
    }

    /**
     * 获取类型和后缀
     *
     * @param url
     * @return
     */
    public static String[] getContentAndRealUrl(String url) {
        if (CheckUtil.strIsEmpty(url) && url.length() <= 1) {
            throw PangException.create(EErrorCode.dataParseError);
        }

        int i = url.indexOf('/', 1);
        if (i < 0) {
            return new String[]{url, ""};
        }

        return new String[]{url.substring(0, i), url.substring(i)};
    }

    /**
     * 获取request的body
     *
     * @param req
     * @return
     */
    public static String getRequestPayload(HttpServletRequest req) {
        StringBuilder sb = new StringBuilder();

        try {
            try (BufferedReader reader = req.getReader()) {
                char[] buff = new char[1024];
                int len;
                while ((len = reader.read(buff)) != -1) {
                    sb.append(buff, 0, len);
                }
            } catch (IOException e) {
                return "";
            }
            return sb.toString();
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 将request参数值转为json
     */

    public static String getRequestParameter(HttpServletRequest request) {
        JSONObject requestJson = new JSONObject();
        Enumeration paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();
            String[] pv = request.getParameterValues(paramName);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < pv.length; i++) {
                if (pv[i].length() > 0) {
                    if (i > 0) {
                        sb.append(",");
                    }
                    sb.append(pv[i]);
                }
            }
            requestJson.put(paramName, sb.toString());
        }
        return requestJson.toString();
    }

    /**
     * get类型获取request的params
     *
     * @param req
     * @return
     */
    public static String getRequestParams(HttpServletRequest req) {
        StringBuilder reqBody = new StringBuilder();
        Enumeration names = req.getParameterNames();
        Map resMap = new TreeMap<>();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            String value = req.getParameter(name);
            resMap.put(name, value);
        }

        Map<String, Object> sortMap = new TreeMap<>(new Comparator<String>() {
            @Override
            public int compare(String str1, String str2) {
                return str1.compareTo(str2);
            }
        });
        sortMap.putAll(resMap);
        String reqBodyStr = "";
        //排序&拼接
        if (CheckUtil.objIsNotEmpty(sortMap)) {
            for (String key : sortMap.keySet()) {
                reqBody.append(key);
                reqBody.append("=");
                reqBody.append(sortMap.get(key));
                reqBody.append("&");
            }
            reqBodyStr = String.valueOf(reqBody).substring(0, reqBody.length() - 1);
        }

        return reqBodyStr;
    }
}








